// 打印机引擎管理器
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/ui/cashier/provider/common_http_provider.dart';
import 'package:flutter_deer/util/print/data/print_format_des.dart';
import 'package:flutter_deer/util/print/data/print_link_type.dart';
import 'package:flutter_deer/util/print/print_engine_gb.dart';
import 'package:flutter_deer/util/speak/tts_manger.dart';
import 'package:get/get.dart';


class PrintEngineManager extends BaseNetProvider {

  final httpProvider = Get.find<CommonHttpProvider>();
  final printEngineGb = PrintEngineGb();

  // 总开关
  final RxBool rxIsOpenPrint = true.obs;

  set isOpenPrint(bool value) {
    rxIsOpenPrint.value = value;
    SpUtil.putBool(Constant.optionSwitchPrint, value);
  }

  // 按客户端打印
  final RxList<String> rxIsOpenPrintByClient = <String>[].obs;

  set isOpenPrintByClient(List<String> value) {
    rxIsOpenPrintByClient.value = value;
    SpUtil.putStringList(Constant.optionSwitchPrintByClient, value);
  }

  List<BroadcastType> get openPrintByClientSelect {
    final list = <BroadcastType>[];
    for (final element in rxIsOpenPrintByClient) {
      for (final value in BroadcastType.values) {
        if (value.indexKey == element) {
          list.add(value);
        }
      }
    }
    return list;
  }

  String get openPrintByClientString {
    final list = rxIsOpenPrintByClient;
    if (list.isEmpty) {
      return '关闭';
    } else if (list.length == BroadcastType.values.length) {
      return '全部';
    } else {
      return '${list.length}/${BroadcastType.values.length}';
    }
  }

  // 按员工打印
  final RxList<String> rxIsOpenPrintByEmployee = <String>[].obs;

  set isOpenPrintByEmployee(List<String> value) {
    rxIsOpenPrintByEmployee.value = value;
    SpUtil.putStringList(Constant.optionSwitchPrintByEmployee, value);
  }

  // 按枪号
  final RxList<String> rxIsOpenPrintByGun = <String>[].obs;

  set isOpenPrintByGun(List<String> value) {
    rxIsOpenPrintByGun.value = value;
    SpUtil.putStringList(Constant.optionSwitchPrintByGun, value);
  }

  // 按支付方式
  final RxList<String> rxIsOpenPrintByPayType = <String>[].obs;

  set isOpenPrintByPayType(List<String> value) {
    rxIsOpenPrintByPayType.value = value;
    SpUtil.putStringList(Constant.optionSwitchPrintByPayType, value);
  }

  // 按小票联数
  final RxList<PrintLinkType> rxPrintLinkType = <PrintLinkType>[].obs;

  set printLinkType(List<PrintLinkType> value) {
    print('object set printLinkType:    ${value.map((e) => e.toJson()).toList()}');
    rxPrintLinkType.value = value;
    // 使用 putObjectList 保存对象列表
    SpUtil.putObjectList(Constant.optionSwitchPrintLinkType, value.map((e) => e.toJson()).toList());
  }

  @override
  void onInit() {
    super.onInit();
    isOpenPrint = SpUtil.getBool(Constant.optionSwitchPrint, defValue: true) == true;
    isOpenPrintByClient = SpUtil.getStringList(Constant.optionSwitchPrintByClient) ?? [];
    isOpenPrintByEmployee = SpUtil.getStringList(Constant.optionSwitchPrintByEmployee) ?? [];
    isOpenPrintByGun = SpUtil.getStringList(Constant.optionSwitchPrintByGun) ?? [];
    isOpenPrintByPayType = SpUtil.getStringList(Constant.optionSwitchPrintByPayType) ?? [];

    // 读取保存的小票联数设置
    final objList = SpUtil.getObjectList(Constant.optionSwitchPrintLinkType);
    print('object get printLinkType:    $objList');
    if (objList != null && objList.isNotEmpty) {
      try {
        final List<PrintLinkType> printLinkTypes = objList.map((item) => PrintLinkType.fromJson(item as Map<String, dynamic>)).toList();
        print('object get printLinkType success:    ${printLinkTypes.map((e) => e.toJson()).toList()}');
        printLinkType = printLinkTypes;
      } catch (e) {
        print('object get printLinkType error:    $e');
        // 如果解析失败，使用默认值
        printLinkType = PrintLinkType.values.toList();
      }
    } else {
      // 如果没有保存的设置，使用默认值
      print('object get printLinkType empty');
      printLinkType = PrintLinkType.values.toList();
    }

    for (final element in PrintLinkType.values) {
      httpProvider.getPrintStyle(element.code);
    }
  }

  // final List<IPrintBaseEngine> _engines = [];

  /// 注册引擎
  void registerEngine() {
    // _engines[name] = engine;
  }

  // 组装打印数据
  void printTicket(Map<String, dynamic> content, PrintLinkType printStyle, {bool rePrint = false}) {
    if (printStyle.linkType == PrintCouplet.NONE.typeCode) {
      return;
    }
    // print('print---> printStyle:${printStyle.linkType}');
    final printBeans = <BasePrintBean>[];
    if (printStyle.linkType == PrintCouplet.BOTH_TWO.typeCode) {
      addPrintParams(content, printStyle, printBeans, rePrint);
      addPrintParams(content, printStyle, printBeans, rePrint);
    } else {
      addPrintParams(content, printStyle, printBeans, rePrint);
    }

    printEngineGb.executePrint(printBeans);
    // for (var value in printBeans) {
    //   print(value.toString());
    // }
  }

  void addPrintParams(Map<String, dynamic> content, PrintLinkType printType, List<BasePrintBean> printBeanList, bool rePrint) {
    if (printType.linkType == PrintCouplet.NONE.typeCode) {
      return;
    }

    final oilInfo = content['oilInfo'] as Map<String, dynamic>;
    final stationName = '${oilInfo['oilName']}';
    printBeanList.add(TextPrintBean(alignment: BasePrintBean.CENTER, text: stationName, textSize: BasePrintBean.TEXT_SIZE_BIG, isBold: true));

    final buda = rePrint ? '补打' : '';
    final ticketName = printType.linkType == PrintCouplet.CUSTOMER.typeCode ? '(客户联$buda)' : '(商户联$buda)';
    printBeanList.add(TextPrintBean(alignment: BasePrintBean.CENTER, text: ticketName, textSize: BasePrintBean.TEXT_SIZE_MID, isBold: false));

    if (content['oilInfo'] == 1) {
      printBeanList.add(TextPrintBean(alignment: BasePrintBean.CENTER, text: '异常订单', textSize: BasePrintBean.TEXT_SIZE_MID, isBold: true));
    }

    final printStyle = PrintLinkType.getPrintStyle(printType.code);
    final mTypeCode = printType.linkType == PrintCouplet.CUSTOMER.typeCode ? 'customerConfig' : 'mchConfig';
    printStyle?.configValue.firstWhereOrNull((e) => e.typeCode == mTypeCode)?.list.forEach((data1) {

      // print('data1: ${data1.toString()}');

      // 处理提示信息和分割线
      if (data1.valueCode == "prompt") {
        data1.itemList.forEach((it) {
          // print('data1->prompt->itemList:$it');
          if (it.checkboxCode == "promptMessage") {
            printBeanList.add(TextPrintBean(alignment: BasePrintBean.CENTER, text: it.checkboxValue, textSize: BasePrintBean.TEXT_SIZE_MID, isBold: true,));
          }
          if (it.checkboxCode == "splitLine") {
            printBeanList.add(DashLinePrintBean());
          }
        });
      } else  {

        // 获取数据对象
        final jobj1 = content[data1.valueCode];
        // 打印出job1的类型
        // print('---[${data1.valueCode}]>job1:${jobj1.runtimeType} ');

        // print('---[${data1.itemList.map((e)=> e.checkboxCode)}] ---> chooseCheckboxCodes:${data1.chooseCheckboxCodes} ');

        // 过滤选中的打印项
        final printList = data1.itemList.where((e) => data1.chooseCheckboxCodes.contains(e.checkboxCode)).toList();
        // print('printList:$printList');

        // 判断是否为表单
        if (jobj1 is Map<String, dynamic>) {
          // print('---[${data1.valueCode}]>job1:$jobj1');
          for (var data2 in printList) {
            if (!data1.chooseCheckboxCodes.contains(data2.checkboxCode)) {
              break;
            } else
            if (data1.chooseCheckboxCodes.contains("budaShow") && rePrint) {
              //"$TAG[发票二维码]  仅补打联-打印 ".dogger()
              break;
            } else
            if (data2.checkboxCode == 'oilName'){
              break;
            } else
            if (data2.checkboxCode == 'budaShow'){
              break;
            } else
            if (data2.checkboxCode == 'splitLine'){
              printBeanList.add(DashLinePrintBean());
              break;
            } else
            if (data2.checkboxCode == 'promptMessage'){
              // printBeanList.add(TextPrintBean(BasePrintBean.CENTER, data2.checkboxValue, BasePrintBean.TEXT_SIZE_MID, true, false))
              printBeanList.add(TextPrintBean(alignment: BasePrintBean.LEFT, text: data2.checkboxValue, textSize: BasePrintBean.TEXT_SIZE_MID, isBold: false));
              break;
            } else
            if (data2.checkboxCode == 'openInvoiceQRCode'){
              printBeanList.add(CodePrintBean(codeData: data2.valueCode, codeType: 2));
              break;
            } else
            if (data1.itemCode == 'keyReminder') {
              printBeanList.add(TextPrintBean(alignment: BasePrintBean.LEFT, text: '${data2.checkboxName}：${jobj1[data2.valueCode]}', textSize: BasePrintBean.TEXT_SIZE_BIG, isBold: true));
              break;
            } else {
              printBeanList.add(TextPrintBean(alignment: BasePrintBean.LEFT, text: '${data2.checkboxName}：${jobj1[data2.valueCode]}', textSize: BasePrintBean.TEXT_SIZE_MID, isBold: false));
            }
          }

        }

        // 判断是否为列表数据
        if (jobj1 is List<dynamic>) {
          if (printList.isEmpty) {
            return;
          }

          var hasLine = false;
          if (printList.isNotEmpty && printList.last.checkboxCode == "splitLine") {
            hasLine = true;
            printList.removeLast();
          }

          final array = printList.map((s) => s.checkboxName).toList();
          final arrayValueCode = printList.map((s) => s.valueCode).toList();

          final listData = jobj1;

          // print('---listData :---------------${listData.runtimeType}-----------');
          if (listData.isNull || listData.isEmpty) {
            printBeanList.add(TextPrintBean(alignment: BasePrintBean.CENTER, text: '暂无数据', textSize: BasePrintBean.TEXT_SIZE_MID, isBold: false));
          } else {
            printBeanList.add(ColumnsTextPrintBean(colsTextArr: array, receiptStyle: printStyle.configKey));
          }

          for (var data in listData) {
            final List<String> ssss = [];
            for (var b in arrayValueCode) {
              ssss.add('${data['$b']}'.replaceAll('null', ''));
            }
            // print('--------------- ${ssss}');
            printBeanList.add(ColumnsTextPrintBean(colsTextArr: ssss, receiptStyle: printStyle.configKey));
          }

          if (hasLine) {
            printBeanList.add(DashLinePrintBean());
          }

        }
      }

    });
  }

  // 组装班结打印数据
  void printShift(Map<String, dynamic> content, PrintLinkType printStyle, {bool rePrint = false}) {

  }
}
